#include "stdafx.h"
#include "TCPServer.h"
#include "Log.h"
#include "System.h"

namespace Core
{
	TCPServer::TCPServer(unsigned short p_PortNumber) : m_Socket(Protocol_Tcp)
	{
		m_PortNumber = p_PortNumber;
		m_Socket.Close();
		Start();
	}

	void TCPServer::InitializeSocket()
	{
		Log::GetSingleton().Write(LogLevel_Info, "Initializing socket for TCP Server on port [" + System::ToString(m_PortNumber) + "]");
		m_Socket = Core::Socket(Core::Protocol_Tcp);
		Core::InternetAddress t_InternetAddress;
		t_InternetAddress.PortNumber = m_PortNumber;
		m_Socket.Bind(t_InternetAddress);
		m_Socket.Listen();
	}

	void TCPServer::Execute()
	{
		if(!m_Socket.IsActive())
		{
			InitializeSocket();
		}
		Log::GetSingleton().Write(LogLevel_Info, "Starting TCP Server on port [" + System::ToString(m_PortNumber) + "]");
		while(m_Socket.IsActive())
		{
			try
			{
				Core::Socket t_Socket = m_Socket.Accept(1000);
				if(t_Socket.GetSocketDescriptor()==0) continue;
				Log::GetSingleton().Write(LogLevel_Info, "TCP Server is receiving connection from [" + t_Socket.GetRemoteAddress().Address + "]");
				ConnectionReceived(t_Socket);
			}
			catch(...)
			{
				m_Socket.Close();
				continue;
			}
		}
		Log::GetSingleton().Write(LogLevel_Info, "Finishing TCP Server on port [" + System::ToString(m_PortNumber) + "]");
	}

	void TCPServer::ConnectionReceived(Socket& p_Socket)
	{
		Log::GetSingleton().Write(LogLevel_Info, "TCP Server is discarding connection from [" + p_Socket.GetRemoteAddress().Address + "] due to no one is handling the connection");
		p_Socket.Close();
	}
}
